package com.qqt.csr.order.service.statemachine.action.impl;

import com.google.common.collect.Lists;
import com.qqt.csr.message.event.intrasite.IntraSiteMessageEventPublisher;
import com.qqt.csr.message.event.intrasite.workorder.WorkOrderEventSource;
import com.qqt.csr.order.entity.WorkOrder;
import com.qqt.csr.order.enums.WorkOrderTemplateType;
import com.qqt.csr.order.service.event.DynamicEventListener;
import com.qqt.csr.order.service.statemachine.context.WorkOrderContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class AbstractWorkOrderProcessor {
    //工单站内信弹窗能否跳转的权限配置
    protected final String ORDER_POOL_PERM="order:pool:*";
    protected final String ORDER_CREATOR_PERM="order:creator:*";
    protected final String ORDER_PROCESSOR_PERM="order:processor:*";
    protected final String ORDER_WORKBENCH_PERM="order:workbench:*";

    @Autowired
    protected IntraSiteMessageEventPublisher messageEventPublisher;
    @Autowired
    protected DynamicEventListener dynamicEventListener;

    /**
     * 发送工单状态变更系统通知到创建人或处理人
     *
     * @param context
     */
    protected void sendChangedOrderStatusMsgNotify(WorkOrderContext context, WorkOrderTemplateType templateType, String linkUrl) {
        WorkOrder fromOrder = context.getFromOrder();
        if (!fromOrder.isAllocated() || !fromOrder.isNeedSysNotify()) {
            return;
        }

        String permission = StringUtils.EMPTY;
        Long recipientId = null;
        if (context.getOperatorId().equals(fromOrder.getCreatorId())) {
            if (!fromOrder.getCreatorId().equals(fromOrder.getDesigneeId())) {
                recipientId = fromOrder.getDesigneeId();
                permission = ORDER_PROCESSOR_PERM;
            }
        } else{
            recipientId = fromOrder.getCreatorId();
            permission = ORDER_CREATOR_PERM;
        }

        if (recipientId != null) {
            WorkOrderEventSource workOrderEventSource = new WorkOrderEventSource()
                    .setWorkOrderId(fromOrder.getId())
                    .setWorkOrderName(fromOrder.getTitle())
                    .setEventType(templateType)
                    .setLinkUrl(linkUrl)
                    .setParams(new String[]{context.getOperatorName()})
                    .setExt("{\"permission\":\""+permission+"\"}")
                    .setRecipientIds(Lists.newArrayList(recipientId));
            messageEventPublisher.publishEvent(workOrderEventSource);
        }
    }
}
